// pages/login/login.js
//云开发
const db = wx.cloud.database()
const driver_account = db.collection('driver_account')
// 账号、密码
let driver_id = ''
let driver_password = ''
//openid
let openid = ''
//几号司机
let number = 0
Page({

  data: {

  },

  onLoad(options) {

  },
  //获取账号
  idChange(e) {
    driver_id = e.detail.value
  },
  //获取密码
  passwordChange(e) {
    driver_password = e.detail.value
  },
  //点击登录按钮
  onLogin() {
    console.log('点击登录按钮')
    if (driver_id === '') {
      wx.showToast({
        title: '账号不能为空',
        icon: 'none',
        duration: 1000
      })
    } else if (driver_password === '') {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none',
        duration: 1000
      })
    } else {
      driver_account.where({
        driver_id: driver_id
      }).get()
        .then(res => {
          console.log(res)
          if (res.data.length !== 0) {
            //验证密码
            if (driver_password === res.data[0].driver_password) {
              //验证账号是否已经被登录
              if (res.data[0].state) {
                wx.showToast({
                  title: '账号被登录了，请更换账号',
                  icon: 'none',
                  duration: 2000
                })
                return
              }
              //开加载框
              wx.showLoading({
                title: '加载中',
              })
              //修改状态state为true
              wx.cloud.callFunction({
                name: 'setDriverAccount',
                data: {
                  number: res.data[0].number,
                  state: true
                }
              }).then(() => {
                // 关闭加载
                wx.hideLoading()
                //跳转到司机页面,携带参数res.data[0].number为司机编号
                wx.reLaunch({
                  url: '/pages/xiaobai/xiaobai?number=' + res.data[0].number + '&driver_id=' + res.data[0].driver_id
                })
                console.log('成功登录')
              })
            } else {
              //密码错误
              wx.showToast({
                title: '密码错误',
                icon: 'none',
                duration: 1000
              })
            }
          } else {
            //账号错误
            wx.showToast({
              title: '账号不存在',
              icon: 'none',
              duration: 1000
            })
          }
        })
    }
  }
})